//
//  WithdrawController.swift
//  mggz
//
//  Created by ShareAnimation on 2017/8/25.
//  Copyright © 2017年 爱丽丝的梦境. All rights reserved.
//

import UIKit
import SwiftProgressHUD
import Moya
import ObjectMapper
class WithdrawController: UIViewController {
    var validTAmount:Double?
    fileprivate var _tableView: UITableView!
    fileprivate var isPayPwdSet:Bool?
    fileprivate var tableView: UITableView {
        get {
            if _tableView != nil {
                return _tableView
            }
            _tableView = UITableView()
            _tableView.delegate = self
            _tableView.dataSource = self
            _tableView.tableFooterView = UIView()
            _tableView.separatorStyle = .none
            _tableView.showsVerticalScrollIndicator = false
            _tableView.backgroundColor = UIColor.mg_backgroundGray
            
            regClass(_tableView, cell: UITableViewCell.self)
            regClass(_tableView, cell: WithdrawCell.self)
            
            return _tableView
        }
    }
    
    //合计Label
    private var amountLabel: UILabel = {
        let label = UILabel()
        label.backgroundColor = UIColor.white
        label.font = wwFont_Medium(17)
        label.textAlignment = .center
        
        return label
    }()
    
    fileprivate lazy var topView:UIView = {
        let topView = UIView()
        topView.backgroundColor = UIColor.white
        let titleLabel = UILabel()
        titleLabel.frame = CGRect(x: 16, y: 0, width: SCREEN_WIDTH-32, height: 80)
        titleLabel.textColor = UIColor(red: 0.80, green: 0.80, blue: 0.80, alpha: 1)
        let titleStr = NSMutableAttributedString.init(string: "* 说明：为了避免劳务纠纷，每笔工资结算以后短期内不支持提现，一段时间以后才能解冻！")
   titleStr.addAttribute(NSAttributedStringKey.foregroundColor, value: UIColor.red, range: NSRange(location: 0, length: 1))
    //titleStr.addAttribute(NSAttributedStringKey.foregroundColor, value: UIColor(red: 0.80, green: 0.80, blue: 0.80, alpha: 1), range: NSRange(location: 1, length: 41))
        
        titleLabel.attributedText = titleStr
        titleLabel.numberOfLines = 0
        titleLabel.font = UIFont.systemFont(ofSize: 15)
        topView.addSubview(titleLabel)
        return topView
    }()
    
    
    fileprivate lazy var amountPayedView:AmountPayView = {
        let amountPayedView = AmountPayView()
    amountPayedView.withDrawButton.addTarget(self, action: #selector(showPaymentView), for: .touchUpInside)
        return amountPayedView
    }()
    
    //提现Button
    private var withdrawButton: UIButton = {
        let button = UIButton()
        button.setTitle("提现", for: .normal)
        button.backgroundColor = UIColor.mg_blue
        button.titleLabel?.font = wwFont_Regular(17)
        return button
    }()
    
    var currentBankCard: BankCardModel? //当前界面的银行卡模型
    var salaryWithdrawModels: [SalaryWithdraw]? //工资提款模型
    
    var selectedCells = [SalaryWithdraw]() {
        willSet {
            self.currentTotalAmount = 0
            if newValue.count > 0 {
                
                for item in newValue {
                    self.currentTotalAmount += item.applyAmount ?? 0
                }
            }
        }
    }//选中的cell
    
    //当前价钱总计
    var currentTotalAmount: Float = 0.0 {
        willSet {
            let tempString = "\(newValue)"
            let totalAmountMoneyFormat = Tool.numberToMoney(tempString)
            self.amountLabel.text = "合计：" + "￥" + (totalAmountMoneyFormat ?? "0")
        }
    }
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        self.checkPayPwd()
    }
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(true)
        WWProgressHUD.dismiss()
    }
    override func viewDidLoad() {
        super.viewDidLoad()
        self.view.backgroundColor = UIColor.mg_backgroundGray
        self.title = "提现"
        //self.amountPayedView.myValidAccount.text = self.validAccount
       self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: "明细", style: .done, target: self, action: #selector(pushDetailWithDraw))
    self.navigationItem.rightBarButtonItem?.setTitleTextAttributes([NSAttributedStringKey.font:UIFont.systemFont(ofSize: 15)], for: .normal)
        
        self.setupViews()
        self.getValidAmountData()
        self.getData()
        
    }
    
    func getValidAmountData() {
        
        guard let accountId = WWUser.sharedInstance.accountId else{
            return
        }
        guard let companyId = WWUser.sharedInstance.companyID else{
            return
        }
        
        LCAPiSubManager.request(.GetAccountAmount(AccountId: accountId, CompanyID: companyId)) { (result) in
            if case let .success(response) = result {
                guard  let jsonString :NSDictionary = try?response.mapJSON() as! NSDictionary else{
                    return
                }
                if let validAmount = jsonString["validAmount"] as? Double{
                    self.validTAmount = validAmount
                    let validAmountObj = NSNumber.init(value: validAmount)
                    
                    let valueString = Tool.numberToMoney("\(validAmountObj)")
                    
                    
                    self.amountPayedView.myValidAccount.text = valueString
                }
            }
        }
    }
    
    
    
    @objc fileprivate func pushDetailWithDraw(){
         let withDrawDetail = NewWithDrawViewController()
    self.navigationController?.pushViewController(withDrawDetail, animated: true)
    }
    fileprivate func checkPayPwd(){
        guard let accountId = WWUser.sharedInstance.accountId else{
            return
        }
        
      LCAPiSubManager.request(.CheckPayPwdExits(AccountId: accountId)) { (result) in
            if case let .success(response) = result {
                guard  let jsonString :NSDictionary = try?response.mapJSON() as! NSDictionary else{
                    return
                }
                guard (jsonString["State"]) as! String == "OK" else{
                    self.isPayPwdSet = false
                    return
                }
                self.isPayPwdSet = true
            }
        }
    }
    func setupViews() {
        self.view.addSubview(self.topView)
        self.topView.snp.makeConstraints { (make) in
            make.right.left.equalTo(self.view)
            make.top.equalTo(self.view).offset(64)
            make.height.equalTo(80)
        }
        
        self.view.addSubview(self.tableView)
        self.tableView.snp.makeConstraints { (make) in
            make.right.left.bottom.equalTo(self.view)
            make.top.equalTo(self.topView.snp.bottom).offset(2)
        }
        self.tableView.addSubview(self.amountPayedView)
        self.amountPayedView.snp.makeConstraints { (make) in
            make.left.right.equalTo(self.view)
            make.top.equalTo(self.tableView).offset(80)
            make.height.equalTo(210)
        }
        
        /*
        let bottomBar = UIView()
        self.view.addSubview(bottomBar)
        bottomBar.snp.makeConstraints { (make) in
            make.left.bottom.right.equalTo(self.view)
            make.top.equalTo(self.tableView.snp.bottom)
            make.height.equalTo(40)
        }
        
        bottomBar.addSubview(self.amountLabel)
        self.amountLabel.snp.makeConstraints { (make) in
            make.left.top.bottom.equalTo(bottomBar)
        }
        
        self.withdrawButton.addTarget(self, action: #selector(showPaymentView), for: .touchUpInside)
        bottomBar.addSubview(self.withdrawButton)
        self.withdrawButton.snp.makeConstraints { (make) in
            make.top.bottom.right.equalTo(bottomBar)
            make.left.equalTo(self.amountLabel.snp.right)
            make.width.equalTo(100)
        }
      */
    }
    
    func doRightAction() {
    self.navigationController?.pushViewController(SetPaymentPasswordController(), animated: true)
    }
    
    //执行提现（密码验证后的步骤）
    func doWithdrawAction() {
        let group = DispatchGroup()
        
        var guid: String?
        var orderNo: String?
        group.enter()
        UserModel.getGuid { (response) in
            if response.success {
                guid = response.value
            }
            else {
                WWError("获取GUID错误")
            }
            group.leave()
        }
        
        group.enter()
        let orderConfigId = "7779fe7e-0dbe-6ae7-135a-c3d5a3a5bdd4"
        CommonModel.getOrderNo(orderConfigId) { (response) in
            if response.success {
                guard let number = response.value else {
        
                    return
                }
                orderNo = number
            }
            else {
                
                WWError(response.message)
            }
            group.leave()
        }
        
        //获取guid和orderNo成功
        group.notify(queue: DispatchQueue.main) {

            guard let bankCard = self.currentBankCard, bankCard.bankCardId != nil else {
                WWInform("没有银行卡")
                return
            }
            
            var salaryDetailIdArr = [String]()
            for item in self.selectedCells {
            guard item.MigrantWorkerSalaryDetailID != nil else{
                return
            }
                
    salaryDetailIdArr.append(item.MigrantWorkerSalaryDetailID!)
            }
            guard guid != nil, orderNo != nil else {
                WWInform("guid或者Orderno是空的")
                return
            }
            
            WWBeginLoading()
            SalaryWithdraw.withdraw(guid!, amount: self.currentTotalAmount, bankCardId: bankCard.bankCardId!, orderNo: orderNo!, migrantWorkerSalaryDetailIDs: salaryDetailIdArr, completionHandler: { (response) in
                if response.success {
                   
                    WWEndLoading()
                    NotificationCenter.default.post(name: NSNotification.Name.init(kNotificationWithdrawComplete), object: nil)
                    
                    let vc = withdrawSuccessNav.init(self.currentBankCard!, amount: self.currentTotalAmount)
                    weak var weakSelf = self
                    vc.withdrawNavHandler = {
                    weakSelf?.getValidAmountData()
                    weakSelf?.amountPayedView.amountTextField.text = nil
                    }
                    self.present(vc, animated: true, completion: {
                    //self.navigationController?.popViewController(animated: true)
                    })
                
                }
                else {
                    WWError(response.message)
                }
            })
        }
    }
    //弹出输入密码支付界面
    @objc func showPaymentView() {
    self.amountPayedView.amountTextField.resignFirstResponder()
        guard let bankCard = self.currentBankCard, bankCard.bankCardId != nil else {
            WWInform("没有银行卡")
            return
        }
        
        guard (self.validTAmount != nil) else {
            WWInform("等待可提现余额")
            return
        }
        
        
//        guard (self.salaryWithdrawModels != nil) else {
//            WWInform("没有可提现余额")
//            return
//        }
//        guard (self.salaryWithdrawModels?.count)! > Int(0) else {
//            WWInform("没有可提现余额")
//            return
//        }
//        guard self.currentTotalAmount > 0.0 else{
//            WWInform("请选择需要提现的工资")
//            return
//        }
        
        guard let currentAmount = self.amountPayedView.amountTextField.text, currentAmount.count > 0 else {
            QWTextonlyHud("请输入金额!", target: self.view)
            return
        }
        self.currentTotalAmount = Float(currentAmount)!
        guard self.currentTotalAmount > 0 else {
            QWTextonlyHud("金额必须大于0", target: self.view)
            return
        }
        
        let validFamout = Float(self.validTAmount!)
        guard validFamout - self.currentTotalAmount > Float(0) || validFamout - self.currentTotalAmount == Float(0) else {
             QWTextonlyHud("可用提现余额不足", target: self.view)
            return
        }
        
        if self.isPayPwdSet == false{
            let alert = UIAlertController(title: "太公民工交易密码未设置，请前往设置！", message: "", preferredStyle: .alert)
            let refuseApp = UIAlertAction(title: "取消", style: .cancel, handler: { (action) in
                
            })
            let gotoAppstore = UIAlertAction(title: "前往设置", style: .default, handler: { (action) in
            self.navigationController?.pushViewController(SetPaymentPasswordController(), animated: true)
            })
            alert.addAction(gotoAppstore)
            alert.addAction(refuseApp)
            self.present(alert, animated: true, completion: {
                
            })
            return
        }
        
        let vc = PaymentController()
        vc.inputPasswordCompletion = {[unowned self](password) in
            self.checkPaymentPassword(password)
        }
        let totalAmountMoneyFormat = Tool.numberToMoney("\(self.currentTotalAmount)")
        vc.moneyDetailLabel.text = "￥" + (totalAmountMoneyFormat ?? "")
        
        self.present(vc, animated: true, completion: nil)
    }
    
    
    //验证支付密码
    func checkPaymentPassword(_ password: String) {
        
        WWBeginLoadingWithStatus("开始验证")
        PaymentPassword.checkPaymentPassword(password) { (response) in
            if response.success {
                if response.success {
                   
                    //                    WWSuccess("密码验证成功,开始提现")
                    WWEndLoading()
                    self.doWithdrawAction()
                    
                }
            }
            else {
                if response.value == .unSet {
                    WWError("交易密码未设置，请设置交易密码")
            self.navigationController?.pushViewController(SetPaymentPasswordController(), animated: true)
                }
                else {
                    WWError(response.message)
                }
            }
        }
    }
    func getData() {
        //默认重置当前选择的银行卡模型
        self.currentBankCard = nil
        self.currentTotalAmount = 0.0
        self.selectedCells = [SalaryWithdraw]()
        
        BankCardModel.getBankCard { (response) in
            if response.success {
                if let arr = response.value, arr.count > 0 {
                    for item in arr {
                        if item.isDefault {
                            self.currentBankCard = item
                        }
                        
                    }
                }
                else {
                  
                    self.currentBankCard = nil
                }
                self.tableView.reloadSections(IndexSet.init(integer: 0), with: .automatic)
            }
            else
            {
                WWError(response.message)
            }
        }
        
//        SalaryWithdraw.getWihtdrawLists { (response) in
//            if response.success {
//                self.salaryWithdrawModels = response.value
//
//            self.tableView.reloadSections(IndexSet.init(integer: 1), with: .automatic)
//            }
//            else {
//                WWError(response.message)
//            }
//        }
    }
}

extension WithdrawController: UITableViewDelegate, UITableViewDataSource {
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if section == 1 {
            return self.salaryWithdrawModels?.count ?? 0
        }
        return 1
    }
    
    func numberOfSections(in tableView: UITableView) -> Int {
        return 2
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        if indexPath.section == 1 {
            return 80
        }
        return 50
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        if indexPath.section == 0 {
//            let cell = getCell(tableView, cell: UITableViewCell.self, indexPath: indexPath)
            let cell = UITableViewCell(style: .value1, reuseIdentifier: "\(UITableViewCell.self)")
            cell.accessoryType = .disclosureIndicator
            cell.detailTextLabel?.textAlignment = .left
            if let bankCard = self.currentBankCard {
                cell.textLabel?.text = bankCard.bankName
                if let bankAccount = bankCard.salaryCardBankAccount {
                    cell.detailTextLabel?.text = "尾号" + lastFourNumbers(bankAccount)
                }
                
            }
            else {
                cell.textLabel?.text = "添加银行卡"
                cell.detailTextLabel?.text = ""
            }

            return cell
        }
        if indexPath.section == 1 {
            let cell = getCell(tableView, cell: WithdrawCell.self, indexPath: indexPath)
            
            if let model = self.salaryWithdrawModels?[indexPath.row] {
                if self.selectedCells.contains(model){
                    cell.isChosen = true
                }
                else {
                    cell.isChosen = false
                }
                
                cell.bind(self.salaryWithdrawModels![indexPath.row])
            }

            return cell
        }
        
        return UITableViewCell()
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        tableView.deselectRow(at: indexPath, animated: true)
        if indexPath.section == 0 {
            let vc = BankCardChoiceController()
            vc.selectionHandler = {[unowned self] in
                self.getData()
            }
            self.navigationController?.pushViewController(vc, animated: true)
        }
        if indexPath.section == 1 {
            let model = self.salaryWithdrawModels![indexPath.row]
            if self.selectedCells.contains(model) {
                for (index,item) in self.selectedCells.enumerated() {
                    if item == model {
                        self.selectedCells.remove(at: index)
                    }
                }
            }
            else {
                self.selectedCells.append(model)
            }
            
            tableView.reloadRows(at: [indexPath], with: .automatic)
        }
    }
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        if section == 1 {
            return 10
        }
        return 0.1
    }
}
